package com.srunpass.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class ListParseUtil {
    public static void main(String[] args) {
        String input = "[[1],[2,3],[4,5,6]]";
        List<List<String>> result = parseStringList(input);
        System.out.println(result);
    }

    public static List<List<String>> parseStringList(String input) {
        List<List<String>> outerList = new ArrayList<>();

        // 去除最外层括号
        String innerContent = input.trim();
        if (innerContent.startsWith("[") && innerContent.endsWith("]")) {
            innerContent = innerContent.substring(1, innerContent.length() - 1);
        }

        // 匹配每个子列表的正则表达式
        Pattern pattern = Pattern.compile("\\[[^\\[\\]]*\\]");
        Matcher matcher = pattern.matcher(innerContent);

        while (matcher.find()) {
            String subListStr = matcher.group();
            // 去除子列表的括号
            String elementsStr = subListStr.substring(1, subListStr.length() - 1);
            // 分割元素，考虑逗号后的空格
            List<String> innerList = Arrays.stream(elementsStr.split(",\\s*"))
                    .filter(e -> !e.isEmpty())
                    .collect(Collectors.toList());
            outerList.add(innerList);
        }

        return outerList;
    }

    public static List<List<Integer>> parseIntegerList(String input) {
        List<List<Integer>> outerList = new ArrayList<>();

        // 去除最外层括号
        String innerContent = input.trim();
        if (innerContent.startsWith("[") && innerContent.endsWith("]")) {
            innerContent = innerContent.substring(1, innerContent.length() - 1);
        }

        // 匹配每个子列表的正则表达式
        Pattern pattern = Pattern.compile("\\[[^\\[\\]]*\\]");
        Matcher matcher = pattern.matcher(innerContent);

        while (matcher.find()) {
            String subListStr = matcher.group();
            // 去除子列表的括号
            String elementsStr = subListStr.substring(1, subListStr.length() - 1);
            // 分割元素，考虑逗号后的空格
            List<Integer> innerList = Arrays.stream(elementsStr.split(",\\s*"))
                    .filter(e -> !e.isEmpty()).map(Integer::parseInt)
                    .collect(Collectors.toList());
            outerList.add(innerList);
        }

        return outerList;
    }
}